from pydantic import BaseModel,Field,ValidationError
from typing import Optional

#案例一
# class User(BaseModel):
#     name:str = Field(...,title='用户名',min_length=2,max_length=20) #...表示为必填
# #用法
# user = User(name='Alex')
# #错误用法
# user = User()

#案例二
# class UserOptional(BaseModel):
#     name:str = Field("老王",title="用户吗") #默认值为老王
# #用法
# user = UserOptional()
# print(user.name)

#案例三

# class Product(BaseModel):
#     price: float = Field(..., gt=0,title="价格") #必须大于0
#     stock: int = Field(..., ge=0) #必须大于等于0
#
# #正确
# product = Product(price=9.9, stock=10)
#
# #错误
# try:
#     Product(price=-5,stock=0)
# except ValidationError as e:
#     print(e.json())

#案例四
# class Address(BaseModel):
#     street: str = Field(...,min_length=1)
#     city: str
#
# class User(BaseModel):
#     name: str = Field(...)
#     address: Address #等价于 address:Address = Field(...)

#正确
# user = User(name="Alex",address=Address(street="Alex",city="Springfield"))

#错误: 缺少address
# user = User(name="boby")

#案例五
# class User(BaseModel):
#     name: str = Field(...)
#     email:Optional[str] = Field(None,title="email")
#
# #正确：不传email
# user =User(name="alex")
# print(user)

#案例六
class Config(BaseModel):
    api_key:str = Field(...)
    timeout:int = Field(10,ge=1)

#正确
config = Config(api_key="secret")
assert config.timeout == 10

#错误
# Config(timeout=1)